//
//  LoginViewController.m
//  Peso Guide
//
//  Created by macbook on 2025/6/5.
//

#import "LoginViewController.h"
#import "CustomWebViewController.h"

@interface LoginViewController ()

@property (nonatomic, strong) dispatch_source_t timer;
@property (nonatomic, strong) UIView *phoneView;
@property (nonatomic, strong) UILabel *phoneLeftLabel;
@property (nonatomic, strong) UITextField *phoneTF;
@property (nonatomic, strong) UIView *codeView;
@property (nonatomic, strong) UITextField *codeTF;
@property (nonatomic, strong) UIButton *codeButton;
@property (nonatomic, strong) UIButton *voiceButton;
@property (nonatomic, strong) UIButton *chooseButton;
@property (nonatomic, strong) UIView *agreeView;
@property (nonatomic, strong) UIButton *loginButton;

@property (nonatomic, strong) NSString *startTime;
@property (nonatomic, strong) NSString *endTime;
@property (nonatomic, assign) BOOL isFirstClickCode;

@property (nonatomic, strong) NSString *lng;
@property (nonatomic, strong) NSString *lat;

@end

@implementation LoginViewController

- (void)dealloc {
    if (self.timer) {
        dispatch_source_cancel(self.timer);
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.isFirstClickCode = YES;
    
    CAGradientLayer *layer = [CAGradientLayer new];
    layer.colors = @[(__bridge id)ColorHex(@"#FFBD31").CGColor, (__bridge id)ColorHex(@"#FFFFFF").CGColor];
    layer.startPoint = CGPointMake(0.0, 0.0);
    layer.endPoint = CGPointMake(0.0, 1);
    layer.frame = CGRectMake(0, 0, KScreenWidth, KScreenHeight);
    [self.view.layer addSublayer:layer];
    
    self.navView.backgroundColor = [UIColor clearColor];
    self.titleLabel.text = [Lang set:@"Sign in"];
    self.titleLabel.font = FONT(FontWeightStyleRegular, 17);
    self.titleLabel.textColor = ColorHex(@"#000000");
    self.backButton.hidden = YES;
    
    UIButton *backButton = [PesoKit createButtonWithFrame:CGRectMake(12, self.navView.height-13-20, 20, 20) backGroundColor:[UIColor clearColor] title:@"" titleColor:[UIColor clearColor] font:[UIFont systemFontOfSize:12]];
    [backButton setBackgroundImage:[UIImage imageNamed:@"ic_backBtn_white"] forState:0];
    [self.navView addSubview:backButton];
    [backButton addTarget:self action:@selector(backButtonClick) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:self.navView];
    [self.view addSubview:self.titleLabel];
    [self.view addSubview:self.backButton];
    
    UIImageView *iconImg = [PesoKit createImageViewWithFrame:CGRectMake((KScreenWidth-165)/2.0, kStarBarHeight+66, 165, 122) imageNamed:@"ic_login_icon"];
    [self.view addSubview:iconImg];
    
    _phoneView = [PesoKit createViewWithFrame:CGRectMake(40, iconImg.bottom+33, KScreenWidth-80, 48) backGroundColor:ColorHex(@"#FFFFFF")];
    _phoneView.clipsToBounds = YES;
    _phoneView.layer.cornerRadius = 8.0f;
    [self.view addSubview:_phoneView];
    
    NSString *user_phone_start = [NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"user_phone_start"]];
    _phoneLeftLabel = [PesoKit createLabelWithFrame:CGRectMake(0, 0, 57, 48) backGroundColor:ColorHex(@"#FFFFFF") text:[AppTools isEmpty:user_phone_start]?@"63":[NSString stringWithFormat:@"%@",user_phone_start] textColor:ColorHex(@"#0E1D31") font:FONT(FontWeightStyleMedium, 18)];
    _phoneLeftLabel.textAlignment = NSTextAlignmentCenter;
    [_phoneView addSubview:_phoneLeftLabel];
    
    _phoneTF = [PesoKit createTextFieldWithFrame:CGRectMake(57, 0, _phoneView.width-57, 48) backGroundColor:ColorHex(@"#FFFFFF") text:@"" textColor:ColorHex(@"#0E1D31") font:FONT(FontWeightStyleMedium, 18) placeholder:[Lang set:@"Enter your phone number"]];
    _phoneTF.keyboardType = UIKeyboardTypeNumberPad;
    [_phoneView addSubview:_phoneTF];
    
    NSString *userEnterPhone = [[NSUserDefaults standardUserDefaults] objectForKey:@"user_phone"];
    if (![AppTools isEmpty:userEnterPhone]) {
        _phoneTF.text = userEnterPhone;
    }

    _codeView = [PesoKit createViewWithFrame:CGRectMake(40, _phoneView.bottom+18, KScreenWidth-80, 48) backGroundColor:ColorHex(@"#FFFFFF")];
    _codeView.clipsToBounds = YES;
    _codeView.layer.cornerRadius = 8.0f;
    [self.view addSubview:_codeView];
    
    _codeTF = [PesoKit createTextFieldWithFrame:CGRectMake(10, 0, _codeView.width-110, 48) backGroundColor:ColorHex(@"#FFFFFF") text:@"" textColor:ColorHex(@"#0E1D31") font:FONT(FontWeightStyleMedium, 18) placeholder:[Lang set:@"Enter verification code"]];
    _codeTF.keyboardType = UIKeyboardTypeNumberPad;
    [_codeView addSubview:_codeTF];
    
    _codeButton = [PesoKit createButtonWithFrame:CGRectMake(_codeView.width-100, 9, 80, 30) backGroundColor:ColorHex(@"#FE7133") title:[Lang set:@"Get code"] titleColor:ColorHex(@"#FFFFFF") font:FONT(FontWeightStyleRegular, 12)];
    _codeButton.clipsToBounds = YES;
    _codeButton.layer.cornerRadius = 15.0f;
    [_codeButton addTarget:self action:@selector(codeButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [_codeView addSubview:_codeButton];
    
    UIImageView *voiceIcon = [PesoKit createImageViewWithFrame:CGRectMake(56, _codeView.bottom+13, 11, 15) imageNamed:@"ic_login_vioce"];
    [self.view addSubview:voiceIcon];
    
    _voiceButton = [PesoKit createButtonWithFrame:CGRectMake(voiceIcon.width+5+56, _codeView.bottom+12, 200, 17) backGroundColor:[UIColor clearColor] title:[Lang set:@"Voice verification"] titleColor:ColorHex(@"#1A7A35") font:FONT(FontWeightStyleRegular, 12)];
    _voiceButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [_voiceButton addTarget:self action:@selector(voiceButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_voiceButton];
        
    _agreeView = [PesoKit createViewWithFrame:CGRectMake(0, KScreenHeight-kSafeBottomHeight-60-44-16-17, KScreenWidth, 17) backGroundColor:[UIColor clearColor]];
    [self.view addSubview:_agreeView];
    
    NSMutableAttributedString *rmbStr = [[NSMutableAttributedString alloc] initWithString:[Lang set:@"I have read and agree with <Privacy agreement>"] attributes:nil];
    NSRange rangeRmb=[[Lang set:@"I have read and agree with <Privacy agreement>"] rangeOfString:[NSString stringWithFormat:@"%@", [Lang set:@"<Privacy agreement>"]]];
    NSDictionary *fontDic=[NSDictionary dictionaryWithObjectsAndKeys:[UIColor colorWithHexString:@"#1A7A35"],NSForegroundColorAttributeName,FONT(FontWeightStyleRegular, 12),NSFontAttributeName, nil];
    [rmbStr addAttributes:fontDic range:rangeRmb];

    
    UILabel *agreementButton = [PesoKit createLabelWithFrame:CGRectMake(42+15+5, 0, KScreenWidth-64, 17) backGroundColor:[UIColor clearColor] text:[Lang set:@"I have read and agree with <Privacy agreement>"] textColor:ColorHex(@"#0E1D31") font:FONT(FontWeightStyleRegular, 12)];
    agreementButton.attributedText = rmbStr;
    agreementButton.userInteractionEnabled = YES;
    agreementButton.numberOfLines = 3;
    [agreementButton sizeToFit];
    [_agreeView addSubview:agreementButton];
    
    CGSize agreeSize = [AppTools sizeWithText:agreementButton.text font:FONT(FontWeightStyleRegular, 12) maxSize:CGSizeMake(KScreenWidth-64, 100)];
    agreementButton.height = ceil(agreeSize.height+10);
    _agreeView.height = ceil(agreeSize.height+10);
    _agreeView.top = (KScreenHeight-kSafeBottomHeight-60-44-16-17)-(ceil(agreeSize.height+10)-17)/2.0;
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(agreementButtonClick)];
    [agreementButton addGestureRecognizer:tapGesture];
    
    _chooseButton = [[UIButton alloc] initWithFrame:CGRectMake(42, KScreenHeight-kSafeBottomHeight-60-44-16-17, 15, 15)];
    [_chooseButton setBackgroundImage:[UIImage imageNamed:@"ic_login_agree_select"] forState:0];
    _chooseButton.selected = YES;
    [_chooseButton addTarget:self action:@selector(chooseButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_chooseButton];
    
    _loginButton = [PesoKit createButtonWithFrame:CGRectMake(48, _chooseButton.bottom+17, KScreenWidth-48*2, 44) backGroundColor:ColorHex(@"#FE7133") title:[Lang set:@"Login"] titleColor:ColorHex([Lang set:@"#FFFFFF"]) font:FONT(FontWeightStyleMedium, 17)];
    _loginButton.clipsToBounds = YES;
    _loginButton.layer.cornerRadius = 22.0f;
    [_loginButton addTarget:self action:@selector(loginButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_loginButton];
    
    // 在需要获取位置的地方调用
    [[LocationManager sharedManager] getCurrentLocationWithSuccess:^(CLLocationCoordinate2D coordinate) {
        DLog(@"get location success：log=%f, lat=%f", coordinate.longitude, coordinate.latitude);
        
        self.lng = [NSString stringWithFormat:@"%f",coordinate.longitude];
        self.lat = [NSString stringWithFormat:@"%f",coordinate.latitude];

        // 使用获取到的经纬度做其他操作...
        
    } failure:^(NSError *error) {
        // 处理错误情况...
    }];
}

- (void)backButtonClick {
    [[AppTools getCurrentVC] dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (void)loginButtonClick {
    //登录
    if (_chooseButton.isSelected == NO) {
        [SVProgressHUD showErrorWithStatus:[Lang set:@"Please agree to the privacy policy"]];
        [SVProgressHUD dismissWithDelay:3.0f];

        return;
    }
    if ([AppTools isEmpty:_phoneTF.text]) {
        [SVProgressHUD showErrorWithStatus:[Lang set:@"Please enter your mobile phone number"]];
        [SVProgressHUD dismissWithDelay:3.0f];

        return;
    }
    if ([AppTools isEmpty:_codeTF.text]) {
        [SVProgressHUD showErrorWithStatus:[Lang set:@"Please enter the verification code"]];
        [SVProgressHUD dismissWithDelay:3.0f];

        return;
    }
    [[AWHttpService service] postWithUrl:@"/trains/interchangeably" params:@{@"my_env":_phoneTF.text,@"changed":_codeTF.text} succ:^(id  _Nonnull responseObject) {
        if (SUCCESS) {
            self.endTime = [DataPointManager getCurrentTimestamp];
            
            NSDictionary *associating = [responseObject safeObjectForKey:@"associating"];
            NSString *mitigate = [NSString stringWithFormat:@"%@",[associating safeObjectForKey:@"mitigate"]];
            [[NSUserDefaults standardUserDefaults] setObject:mitigate forKey:@"user_token"];
            [[NSUserDefaults standardUserDefaults] setObject:self.phoneTF.text forKey:@"user_phone"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            [[AppTools getCurrentVC] dismissViewControllerAnimated:YES completion:^{}];
            
            [self upLoadData];
            
        }else {
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",[responseObject safeObjectForKey:@"order"]]];
            [SVProgressHUD dismissWithDelay:3.0f];

        }
    } fail:^(NSInteger errorType, id  _Nonnull error) {}];
}

- (void)agreementButtonClick {
    //查看协议
    NSString *user_yinsi = [NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"user_yinsi"]];
    CustomWebViewController *webVC = [[CustomWebViewController alloc] init];
    webVC.modalPresentationStyle = UIModalPresentationFullScreen;
    webVC.isPresent = YES;
    webVC.linkUrl = user_yinsi;
    [self presentViewController:webVC animated:YES completion:^{}];
}

- (void)chooseButtonClick:(UIButton *)sender {
    if (sender.isSelected == NO) {
        sender.selected = YES;
        [_chooseButton setBackgroundImage:[UIImage imageNamed:@"ic_login_agree_select"] forState:0];
    }else {
        sender.selected = NO;
        [_chooseButton setBackgroundImage:[UIImage imageNamed:@"ic_login_agree"] forState:0];
    }
}

- (void)codeButtonClick:(UIButton *)sender {
    if ([AppTools isEmpty:_phoneTF.text]) {
        [SVProgressHUD showErrorWithStatus:[Lang set:@"Please enter your mobile phone number"]];
        [SVProgressHUD dismissWithDelay:3.0f];

        return;
    }
    
    [_codeTF becomeFirstResponder];
    
    [[AWHttpService service] postWithUrl:@"/trains/modifying" params:@{@"env":self.phoneTF.text} succ:^(id  _Nonnull responseObject) {
        if (SUCCESS) {
            [self getCode];
            NSString *order = [NSString stringWithFormat:@"%@",[responseObject safeObjectForKey:@"order"]];
            [SVProgressHUD showSuccessWithStatus:order];
            [SVProgressHUD dismissWithDelay:3.0f];

        }else {
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",[responseObject safeObjectForKey:@"order"]]];
            [SVProgressHUD dismissWithDelay:3.0f];

        }
    } fail:^(NSInteger errorType, id  _Nonnull error) {}];
    
    if (self.isFirstClickCode == YES) {
        self.startTime = [DataPointManager getCurrentTimestamp];
        self.isFirstClickCode = NO;
    }
}

- (void)voiceButtonClick:(UIButton *)sender {
    if ([AppTools isEmpty:_phoneTF.text]) {
        [SVProgressHUD showErrorWithStatus:[Lang set:@"Please enter your mobile phone number"]];
        [SVProgressHUD dismissWithDelay:3.0f];

        return;
    }
    
    [_codeTF becomeFirstResponder];

    [[AWHttpService service] postWithUrl:@"/trains/self" params:@{@"env":self.phoneTF.text} succ:^(id  _Nonnull responseObject) {
        if (SUCCESS) {
            [self getCode];
            NSString *order = [NSString stringWithFormat:@"%@",[responseObject safeObjectForKey:@"order"]];
            [SVProgressHUD showSuccessWithStatus:order];
            [SVProgressHUD dismissWithDelay:3.0f];

        }else {
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",[responseObject safeObjectForKey:@"order"]]];
            [SVProgressHUD dismissWithDelay:3.0f];

        }
    } fail:^(NSInteger errorType, id  _Nonnull error) {}];
    
    if (self.isFirstClickCode == YES) {
        self.startTime = [DataPointManager getCurrentTimestamp];
        self.isFirstClickCode = NO;
    }
}

#pragma mark - GCD
- (void)getCode {
    WeakSelf;
    __block int timeout = 60; ///倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(_timer, ^{
    if(timeout <= 0){
        dispatch_source_cancel(weakSelf.timer);
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.codeButton setTitle:[Lang set:@"Get code"] forState:UIControlStateNormal];
            weakSelf.codeButton.userInteractionEnabled = YES;
    });
    }else{
        dispatch_async(dispatch_get_main_queue(), ^{
            weakSelf.codeButton.backgroundColor = ColorHex(@"#CFCFCF");
            [weakSelf.codeButton setTitle:[NSString stringWithFormat:@"%dS",timeout] forState:UIControlStateNormal];
            weakSelf.codeButton.userInteractionEnabled = NO;
        });
        timeout--;
    }
        });
    dispatch_resume(_timer);
}

- (void)upLoadData {
    [[DataPointManager sharedManager] senRequestWithType:@"1" startTime:self.startTime endTime:self.endTime lng:self.lng lat:self.lat orderId:@""];
//    [[DataPointManager sharedManager] logEventWithType:@"1" startTime:self.startTime endTime:self.endTime orderId:@""];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
